package com.intellagric.service.sys_menu;


import com.intellagric.common.bean.LayuiDataGridResult;
import com.intellagric.common.bean.ResponseMessage;
import com.intellagric.interfaces.sys_menu.MenuService;

import com.intellagric.mapper.SysMenuMapper;
import com.intellagric.mapper.SysRoleMenuMapper;
import com.intellagric.pojo.SysMenu;
import com.intellagric.pojo.SysMenuExample;
import com.intellagric.pojo.SysRoleMenuExample;
import com.intellagric.pojo.SysRoleMenuKey;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;

/**
 * @Auther: zhy
 * @Date: 2018/10/4
 * @Description: 菜单管理服务
 */
@Service
public class MenuServiceImpl implements MenuService {

    @Autowired
    private SysMenuMapper sysMenuMapper;
    @Autowired
    private SysRoleMenuMapper sysRoleMenuMapper;

    /**
     * 添加菜单
     * @Param sysMenu
     * @return ResponseMessage
     */
    @Override
    public ResponseMessage addMenu(SysMenu sysMenu) {


        if (sysMenuMapper.insert(sysMenu) == 1) {
            //添加成功后就在role_menu表，为超级管理员 roleid=1 添加新的menuId
            //这样超级管理员登陆后才可以管理这个新添加的菜单栏
            SysRoleMenuKey  sysRoleMenuKey=new SysRoleMenuKey();
            sysRoleMenuKey.setRoleId("1");
            sysRoleMenuKey.setMenuId(sysMenu.getId());

            //因为layui中有bug，如果添加0级节点就不可以显示，只有再在该结点添加 一个子节点才可以显示
            if("0".equals(sysMenu.getParentId())){
                SysMenu childMenu=new SysMenu();
                childMenu.setId(UUID.randomUUID().toString().replaceAll("-",""));
                SysMenuExample example=new SysMenuExample();
                example.createCriteria().andParentIdEqualTo("0").andHrefEqualTo(sysMenu.getHref()).andNameEqualTo(sysMenu.getName());
                List<SysMenu> sys=sysMenuMapper.selectByExample(example);
                childMenu.setParentId(sys.get(0).getId());
                childMenu.setName("示例菜单");
                //childMenu.setHref("tip.jsp");//提示修改的页面
                childMenu.setCreateDate(sysMenu.getCreateDate());
                childMenu.setUpdateDate(sysMenu.getUpdateDate());
                childMenu.setDelFlag("0");
                sysMenuMapper.insert(childMenu);
                //后面也应该为超级管理员“1”添加上这个菜单的，这里省略了
            }

            if(sysRoleMenuMapper.insert(sysRoleMenuKey)==1)
                return ResponseMessage.success();
        } else {
            return ResponseMessage.fail();
        }
        return ResponseMessage.fail();
    }

    /**
     * 根据menu的Id删除菜单
     * @Param id
     * @return ResponseMessage
     */
    @Override
    public ResponseMessage deleteMenu(String id) {
        //这里没有处理删除父类结点需要的循环删除该结点的子节点

        //先删除角色和菜单的管理表
//        SysRoleMenuExample sysRoleMenuExample=new SysRoleMenuExample();
//        sysRoleMenuExample.createCriteria().andMenuIdEqualTo(id);
//

//        sysRoleMenuMapper.countByExample(sysRoleMenuExample);

//        if(sysRoleMenuMapper.deleteByExample(sysRoleMenuExample)==1) {
//            System.out.println("sysRoleMenu删除成功");
            //在配置文件配置了切面，这里如果不成功应该会回滚把
            if (sysMenuMapper.deleteByPrimaryKey(id) == 1) {
                return ResponseMessage.success();
            } else {
                return ResponseMessage.fail();
            }
//        }

//            return ResponseMessage.fail();
    }

    /**
     * 修改菜单
     * @Param sysMenu
     * @return ResponseMessage
     */
    @Override
    public ResponseMessage editMenu(SysMenu sysMenu) {
        if (sysMenuMapper.updateByPrimaryKeySelective(sysMenu) == 1) {
            return ResponseMessage.success();
        } else {
            return ResponseMessage.fail();
        }
    }

    @Override
    public SysMenu getMenuById(String id) {
        return sysMenuMapper.selectByPrimaryKey(id);
    }

    /**
     * 查询菜单数据信息，生成树形菜单
     * @return LayuiDataGridResult
     */
    @Override
    public LayuiDataGridResult getMenu() {
        //查询所有列表数据
        LayuiDataGridResult result = new LayuiDataGridResult();
        List<SysMenu> menuList = this.getMenuList().getData();
        result.setData(menuList);

        //查询顶级菜单
        List<SysMenu> rootSysMenuList = this.getMenuByParentId("0").getData();

        //生成树形菜单数据，为一级菜单设置子菜单，getChild是递归调用的
        for (SysMenu sysMenu : rootSysMenuList) {
            sysMenu.setChildren(getChild(sysMenu.getId(), menuList));
        }





        result.setData(rootSysMenuList);

        return result;
    }

    private List<SysMenu> getChild(String id, List<SysMenu> menuList) {
        // 子菜单
        List<SysMenu> childList = new ArrayList<SysMenu>();

        // 遍历所有节点，将父菜单id与传过来的id比较
        for (SysMenu sysMenu : menuList) {
            if (sysMenu.getParentId() != null) {   //所有非以及菜单的都要加入chidList中（递归）
                if (sysMenu.getParentId().equals(id)) {
                    childList.add(sysMenu);
                }
            }
        }
        //排序
        Collections.sort(childList, new Comparator<SysMenu>() {
            @Override
            public int compare(SysMenu o1, SysMenu o2) {
                return o1.getSort() < o2.getSort() ? 1 : -1;//降序排列
            }
        });


        // 把子菜单的子菜单再循环一遍
        for (SysMenu sysMenu : childList) {// 没有url子菜单还有子菜单（暂不考虑url的问题）
            // 递归
            sysMenu.setChildren(getChild(sysMenu.getId(), menuList));
        } // 递归退出条件
        if (childList.size() == 0) {
            return null;
        }
        return childList;
    }

    /**
     * 异步查询菜单，通过父id查询
     * @Param parentId
     * @return LayuiDataGridResult
     */
    @Override
    public LayuiDataGridResult getMenuByParentId(String parentId) {
        SysMenuExample sysMenuExample = new SysMenuExample();
        sysMenuExample.setOrderByClause("sort DESC");//以sort字段进行排序
        sysMenuExample.createCriteria().andParentIdEqualTo(parentId);
        List<SysMenu> rootSysMenuList = sysMenuMapper.selectByExample(sysMenuExample);
        LayuiDataGridResult result = new LayuiDataGridResult();
        result.setData(rootSysMenuList);
        return result;
    }

    /**
     * 查询菜单列表信息
     * @return LayuiDataGridResult
     */
    @Override
    public LayuiDataGridResult getMenuList() {
        SysMenuExample sysMenuExample = new SysMenuExample();
        sysMenuExample.setOrderByClause("sort DESC");//以sort字段进行排序
        sysMenuExample.createCriteria().andIdIsNotNull();
        List<SysMenu> sysMenuList = sysMenuMapper.selectByExample(sysMenuExample);
        LayuiDataGridResult result = new LayuiDataGridResult();
        result.setData(sysMenuList);
        return result;
    }



}
